<template>
  <main class="w-full h-full dark:bg-black p-4">
    <use-table
      :total="total"
      :loading="loading"
      :search-select-option="searchSelectOption"
      :columns="columns"
      :personalized="true"
      :all-data="allData"
      @delete-select-user="deleteSelectTest"
      @modify-user-data="modifyTestData"
    >
      <template #function>
        <a-tooltip placement="bottom">
          <template #title>
            <span>添加考试</span>
          </template>
          <div class="cursor-pointer text-lg text-blue-500 mr-2" @click="addTestFormVisible = true">
            <plus-circle-outlined />
          </div>
        </a-tooltip>
      </template>
      <template #title> 考试管理 </template>
    </use-table>
    <modify-form
      v-model:visible="addTestFormVisible"
      modal-title-text="添加考试"
      @handleOk="handleAddTest"
    >
      <template #container>
        <div class="flex items-center">
          <span class="w-22 text-right"> 考试名称： </span>
          <a-input v-model:value="addTestForm.test_name" />
        </div>
        <div class="flex items-center mt-3">
          <span class="w-22 text-right"> 考试介绍： </span>
          <a-textarea v-model:value="addTestForm.exam_introduction" auto-size />
        </div>
        <div class="flex items-center mt-3">
          <span class="w-18 text-right"> 截止时间： </span>
          <a-date-picker
            show-time
            v-model:value="addTestForm.exam_deadline"
            :format="'YYYY-MM-DD HH:mm:ss'"
            :disabledDate="disabledDate"
            placeholder="选择考试截至日期"
            @ok="onPanelChange"
          />
        </div>
        <div class="flex items-center mt-3">
          <span class="w-18 text-right"> 限制时间： </span>
          <a-input v-model:value="addTestForm.time_limit" style="width: 80px" />
          <span class="ml-2">分钟</span>
        </div>
        <div class="flex items-center mt-3">
          <span class="w-18 text-right"> 所属科目： </span>
          <a-select v-model:value="addTestForm.subject_name" style="width: 180px">
            <a-select-option v-for="i in subjectList" :value="i.subject_name">
              {{ i.subject_name }}
            </a-select-option>
          </a-select>
        </div>
        <div class="flex items-center mt-3">
          <span class="w-18 text-right"> 状态： </span>
          <a-switch
            :checked="addTestForm.status === 0 ? false : true"
            @click="addTestForm.status === 0 ? (addTestForm.status = 1) : (addTestForm.status = 0)"
            checked-children="启用"
            un-checked-children="禁用"
          ></a-switch>
        </div>
        <div class="flex items-center mt-3" @click="openAddTestTopicForm(1)">
          <span class="w-18 text-right"> 单选题： </span>
          <a-button> 选择题目（{{ addTestForm.singles.length }}/20） </a-button>
        </div>
        <div class="flex items-center mt-3" @click="openAddTestTopicForm(2)">
          <span class="w-18 text-right"> 多选题： </span>
          <a-button> 选择题目（{{ addTestForm.selections.length }}/20） </a-button>
        </div>
        <div class="flex items-center mt-3" @click="openAddTestTopicForm(3)">
          <span class="w-18 text-right"> 判断题： </span>
          <a-button> 选择题目（{{ addTestForm.judges.length }}/20） </a-button>
        </div>
      </template>
    </modify-form>
    <modify-form
      v-model:visible="modifyTestFormVisible"
      modal-title-text="修改考试"
      @handleOk="handlModifyTest"
    >
      <template #container>
        <div class="flex items-center">
          <span class="w-22 text-right"> 考试名称： </span>
          <a-input v-model:value="modifyTestForm.test_name" />
        </div>
        <div class="flex items-center mt-3">
          <span class="w-22 text-right"> 考试介绍： </span>
          <a-textarea v-model:value="modifyTestForm.exam_introduction" auto-size />
        </div>
        <div class="flex items-center mt-3">
          <span class="w-18 text-right"> 截止时间： </span>
          <a-date-picker
            show-time
            :disabledDate="disabledDate"
            :format="'YYYY-MM-DD HH:mm:ss'"
            placeholder="选择考试截至日期"
            v-model:value="modifyTestForm.exam_deadline"
            @ok="onPanelChange"
          />
        </div>
        <div class="flex items-center mt-3">
          <span class="w-18 text-right"> 限制时间： </span>
          <a-input v-model:value="modifyTestForm.time_limit" style="width: 80px" />
          <span class="ml-2">分钟</span>
        </div>
        <div class="flex items-center mt-3">
          <span class="w-18 text-right"> 所属科目： </span>
          <a-select v-model:value="modifyTestForm.subject_name" style="width: 180px">
            <a-select-option v-for="i in subjectList" :value="i.subject_name">
              {{ i.subject_name }}
            </a-select-option>
          </a-select>
        </div>
        <div class="flex items-center mt-3">
          <span class="w-18 text-right"> 状态： </span>
          <a-switch
            :checked="modifyTestForm.status === 0 ? false : true"
            @click="
              modifyTestForm.status === 0
                ? (modifyTestForm.status = 1)
                : (modifyTestForm.status = 0)
            "
            checked-children="启用"
            un-checked-children="禁用"
          ></a-switch>
        </div>
        <div class="flex items-center mt-3" @click="openModifyTestTopicForm(1)">
          <span class="w-18 text-right"> 单选题： </span>
          <a-button> 选择题目（{{ modifyTestForm.singles.length }}/20） </a-button>
        </div>
        <div class="flex items-center mt-3" @click="openModifyTestTopicForm(2)">
          <span class="w-18 text-right"> 多选题： </span>
          <a-button> 选择题目（{{ modifyTestForm.selections.length }}/20） </a-button>
        </div>
        <div class="flex items-center mt-3" @click="openModifyTestTopicForm(3)">
          <span class="w-18 text-right"> 判断题： </span>
          <a-button> 选择题目（{{ modifyTestForm.judges.length }}/20） </a-button>
        </div>
      </template>
    </modify-form>

    <a-drawer
      v-model:visible="addTopicTestFormVisible"
      class="custom-class"
      @close="close"
      title="选择题目"
      placement="right"
    >
      <div class="flex items-center mb-3">
        <span class="dark:text-light-900 mr-2"> 筛选科目: </span>
        <a-select v-model:value="screeningTopicValue" style="width: 180px" size="small">
          <a-select-option value="null"> 无 </a-select-option>
          <a-select-option v-for="i in subjectList" :value="i.subject_name">
            {{ i.subject_name }}
          </a-select-option>
        </a-select>
      </div>
      <div class="flex items-center mb-3">
        <span class="dark:text-light-900 mr-2"> 搜索题目: </span>
        <a-input
          v-model:value="addTopicSearchValue"
          style="width: 180px"
          @change="handleSearchTopic"
          size="small"
        />
      </div>
      <template v-if="addTopicId === 1">
        <a-checkbox-group
          v-model:value="(addTestForm.singles as number[])"
          name="addSingles"
          :options="searchTopicList"
        />
      </template>
      <template v-else-if="addTopicId === 2">
        <a-checkbox-group
          v-model:value="(addTestForm.selections as number[])"
          name="addSelections"
          :options="searchTopicList"
        />
      </template>
      <template v-else-if="addTopicId === 3">
        <a-checkbox-group
          v-model:value="(addTestForm.judges as number[])"
          name="addJudges"
          :options="searchTopicList"
        />
      </template>
    </a-drawer>

    <a-drawer
      v-model:visible="modifyTopicTestFormVisible"
      @close="close"
      class="custom-class"
      title="修改题目"
      placement="right"
    >
      <div class="flex items-center mb-3">
        <span class="dark:text-light-900 mr-2"> 筛选科目: </span>
        <a-select v-model:value="screeningModifyTopicValue" style="width: 180px" size="small">
          <a-select-option value="null"> 无 </a-select-option>
          <a-select-option v-for="i in subjectList" :value="i.subject_name">
            {{ i.subject_name }}
          </a-select-option>
        </a-select>
      </div>
      <div class="flex items-center mb-3">
        <span class="dark:text-light-900 mr-2"> 搜索题目: </span>
        <a-input
          v-model:value="modifyTopicSearchValue"
          style="width: 180px"
          @change="handleModifySearchTopic"
          size="small"
        />
      </div>
      <template v-if="modifyTopicId === 1">
        <a-checkbox-group
          v-model:value="(modifyTestForm.singles as number[])"
          name="addSingles"
          :options="modifySearchTopicList"
        />
      </template>
      <template v-else-if="modifyTopicId === 2">
        <a-checkbox-group
          v-model:value="(modifyTestForm.selections as number[])"
          name="addSelections"
          :options="modifySearchTopicList"
        />
      </template>
      <template v-else-if="modifyTopicId === 3">
        <a-checkbox-group
          v-model:value="(modifyTestForm.judges as number[])"
          name="addJudges"
          :options="modifySearchTopicList"
        />
      </template>
    </a-drawer>
  </main>
</template>

<script setup lang="ts">
  import {
    TestInfo,
    AddTest,
    ModifyTest,
    SubJect,
    RadioData,
    SelectData,
    JudgeData,
  } from '@/utils/interface';
  import {
    getTests,
    deleteTest,
    addTest,
    getRadioList,
    getAllSelect,
    getAllJudges,
    updateTest,
  } from '@/api/examination';
  import { getSubject } from '@/api/student';
  import { message } from 'ant-design-vue';
  import { PlusCircleOutlined } from '@ant-design/icons-vue';
  import dayjs from 'dayjs';
  let total = ref(0);
  let loading = ref(false);
  const searchSelectOption: { value: string; label: string }[] = [
    {
      value: 'subject_name',
      label: '所属科目',
    },
    {
      value: 'test_name',
      label: '考试名称',
    },
  ];
  const columns = [
    {
      title: '考试名称',
      dataIndex: 'test_name',
      align: 'center',
      width: 220,
      ellipsis: true,
    },
    {
      title: '截止时间',
      dataIndex: 'exam_deadline',
      align: 'center',
      width: 180,
      ellipsis: true,
    },
    {
      title: '考试时间(分钟)',
      dataIndex: 'time_limit',
      align: 'center',
      width: 140,
      ellipsis: true,
    },
    {
      title: '考试介绍',
      dataIndex: 'exam_introduction',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      width: 100,
      ellipsis: true,
    },
    {
      title: '所属科目',
      dataIndex: 'subject_name',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      align: 'center',
      width: 120,
    },
  ];
  let allData = ref<TestInfo[]>([]);
  const getAllTest = async () => {
    loading.value = true;
    const { data } = await getTests();
    allData.value = data;
    total.value = data.length;
    loading.value = false;
  };
  getAllTest();
  let radioList = ref<{ key: number; value: string; label: string; subject: string }[]>([]);
  let selectList = ref<{ key: number; value: string; label: string; subject: string }[]>([]);
  let judgeList = ref<{ key: number; value: string; label: string; subject: string }[]>([]);
  const getAllRadio = async () => {
    const { data: resData } = await getRadioList();
    const data = resData.filter((item) => item.status !== 0);
    radioList.value = data.map((item: RadioData) => {
      return {
        id: item.key,
        value: item.key,
        label: item.single_name,
        subject: item.subject_name,
      };
    });
  };
  const getSelectList = async () => {
    const { data: resData } = await getAllSelect();
    const data = resData.filter((item) => item.status !== 0);
    selectList.value = data.map((item: SelectData) => {
      return {
        id: item.key,
        value: item.key,
        label: item.selection_name,
        subject: item.subject_name,
      };
    });
  };
  const getJudgeList = async () => {
    const { data: resData } = await getAllJudges();
    const data = resData.filter((item) => item.status !== 0);
    judgeList.value = data.map((item: JudgeData) => {
      return {
        id: item.key,
        value: item.key,
        label: item.judge_name,
        subject: item.subject_name,
      };
    });
  };
  getSelectList();
  getAllRadio();
  getJudgeList();

  interface TopicList {
    key: number;
    value: string;
    label: string;
    subject: string;
  }
  let addTopicTestFormVisible = ref(false);
  let topicList = ref<TopicList[]>([]);
  let searchTopicList = ref<TopicList[]>([]);
  let addTopicId = ref(0);
  let screeningTopicValue = ref('');
  let addTopicSearchValue = ref('');
  const openAddTestTopicForm = (id: number) => {
    addTopicId.value = id;
    switch (id) {
      case 1:
        topicList.value = radioList.value;
        break;
      case 2:
        topicList.value = selectList.value;
        break;
      case 3:
        topicList.value = judgeList.value;
    }
    searchTopicList.value = topicList.value;
    addTopicTestFormVisible.value = true;
  };
  watch(
    () => screeningTopicValue.value,
    (val) => {
      if (val === 'null') {
        searchTopicList.value = topicList.value;
      } else {
        searchTopicList.value = topicList.value.filter((item) => item.subject === val);
      }
    }
  );
  const handleSearchTopic = () => {
    if (
      addTopicSearchValue.value === '' &&
      (screeningTopicValue.value === '' || screeningTopicValue.value === 'null')
    ) {
      searchTopicList.value = topicList.value;
    } else {
      if (screeningTopicValue.value !== '' && screeningTopicValue.value !== 'null') {
        searchTopicList.value = topicList.value.filter(
          (item) =>
            item.label.indexOf(addTopicSearchValue.value) !== -1 &&
            item.subject === screeningTopicValue.value
        );
      } else {
        searchTopicList.value = topicList.value.filter(
          (item) => item.label.indexOf(addTopicSearchValue.value) !== -1
        );
      }
    }
  };

  let modifyTopicTestFormVisible = ref(false);
  let modifyTopicList = ref<TopicList[]>([]);
  let modifySearchTopicList = ref<TopicList[]>([]);
  let modifyTopicId = ref(0);
  let screeningModifyTopicValue = ref('');
  let modifyTopicSearchValue = ref('');
  const openModifyTestTopicForm = (id: number) => {
    modifyTopicId.value = id;
    switch (id) {
      case 1:
        modifyTopicList.value = radioList.value;
        break;
      case 2:
        modifyTopicList.value = selectList.value;
        break;
      case 3:
        modifyTopicList.value = judgeList.value;
    }
    modifySearchTopicList.value = modifyTopicList.value;
    modifyTopicTestFormVisible.value = true;
  };
  watch(
    () => screeningModifyTopicValue.value,
    (val) => {
      if (val === 'null') {
        modifySearchTopicList.value = modifyTopicList.value;
      } else {
        modifySearchTopicList.value = modifyTopicList.value.filter((item) => item.subject === val);
      }
    }
  );
  const handleModifySearchTopic = () => {
    if (
      modifyTopicSearchValue.value === '' &&
      (screeningModifyTopicValue.value === '' || screeningModifyTopicValue.value === 'null')
    ) {
      modifySearchTopicList.value = modifyTopicList.value;
    } else {
      if (screeningModifyTopicValue.value !== '' && screeningModifyTopicValue.value !== 'null') {
        modifySearchTopicList.value = modifyTopicList.value.filter(
          (item) =>
            item.label.indexOf(modifyTopicSearchValue.value) !== -1 &&
            item.subject === screeningModifyTopicValue.value
        );
      } else {
        modifySearchTopicList.value = modifyTopicList.value.filter(
          (item) => item.label.indexOf(modifyTopicSearchValue.value) !== -1
        );
      }
    }
  };

  const deleteSelectTest = async (key: number[]) => {
    const active = allData.value.find((item) => item.key === key[0]);
    if (active?.status === 1) {
      message.warning('考试已发布，请先取消发布！');
      return;
    }
    const { status, msg } = (await deleteTest(key)) as any;
    if (status === 200) {
      message.success(msg);
      getAllTest();
    }
  };

  let subjectList = ref<SubJect[]>([]);
  const getSubjectList = async () => {
    const { data } = await getSubject();
    subjectList.value = data as SubJect[];
  };
  getSubjectList();
  const disabledDate = (current) => {
    return current && current.valueOf() < Date.now();
  };
  let addTestFormVisible = ref(false);
  let addTestForm = ref<AddTest>({
    test_name: '',
    exam_introduction: '',
    exam_deadline: '',
    time_limit: '',
    subject_name: '',
    status: 0,
    judges: [],
    selections: [],
    singles: [],
  });
  const onPanelChange = (date: any) => {
    let d = `${String(date.$y)}-${String(date.$M + 1)}-${String(date.$D)} ${String(
      date.$H
    )}:${String(date.$m)}:${String(date.$s)}`;
    addTestForm.value.exam_deadline = dayjs(d) as any;
    modifyTestForm.value.exam_deadline = dayjs(d) as any;
  };
  const handleAddTest = async () => {
    const {
      test_name,
      exam_deadline,
      exam_introduction,
      time_limit,
      subject_name,
      judges,
      selections,
      singles,
    } = addTestForm.value;

    if (
      !test_name ||
      !exam_deadline ||
      !exam_introduction ||
      !time_limit ||
      !subject_name ||
      !judges.length ||
      !selections.length ||
      !singles.length
    ) {
      message.warning('请填写完整信息！');
      return;
    }
    let d = dayjs(addTestForm.value.exam_deadline).format('YYYY-MM-DD HH:mm:ss');

    const { status, msg } = (await addTest({
      ...addTestForm.value,
      exam_deadline: d,
    })) as any;
    if (status === 200) {
      message.success(msg);
      addTestFormVisible.value = false;
      getAllTest();
      addTestForm.value = {
        test_name: '',
        exam_introduction: '',
        exam_deadline: '',
        time_limit: '',
        subject_name: '',
        status: 0,
        judges: [],
        selections: [],
        singles: [],
      };
    }
  };

  let modifyTestForm = ref<ModifyTest>({
    test_name: '',
    exam_introduction: '',
    exam_deadline: '',
    time_limit: '',
    subject_name: '',
    status: 0,
    judges: [],
    selections: [],
    singles: [],
    key: 0,
  });
  let modifyTestFormVisible = ref(false);
  let modifyTestData = (key: number) => {
    let active = allData.value.find((item) => item.key === key) as any;

    if (!active) {
      message.error('发生错误，请刷新页面！');
      return;
    }

    active = {
      ...active,
      exam_deadline: dayjs(active.exam_deadline) as any,
      singles: active.singles.map((item) => item.key),
      selections: active.selections.map((item) => item.key),
      judges: active.judges.map((item) => item.key),
    };
    modifyTestForm.value = active as any;
    modifyTestFormVisible.value = true;
  };

  const handlModifyTest = async () => {
    const {
      test_name,
      exam_deadline,
      exam_introduction,
      time_limit,
      subject_name,
      status: testStatus,
      selections,
      singles,
      judges,
      key,
    } = toRefs(modifyTestForm.value);
    const d = dayjs(exam_deadline.value).format('YYYY-MM-DD HH:mm:ss');

    if (
      !test_name.value ||
      !exam_deadline.value ||
      !exam_introduction.value ||
      !time_limit.value ||
      !subject_name.value
    ) {
      message.warning('请填写完整信息！');
      return;
    }

    const { status, msg } = (await updateTest({
      test_name: test_name.value,
      exam_deadline: d,
      exam_introduction: exam_introduction.value,
      time_limit: time_limit.value,
      subject_name: subject_name.value,
      status: testStatus.value,
      selections: selections.value,
      singles: singles.value,
      judges: judges.value,
      id: key?.value,
    })) as any;

    if (status === 200) {
      message.success(msg);
      modifyTestFormVisible.value = false;
      getAllTest();
    }
  };

  const close = () => {
    screeningTopicValue.value = 'null';
    addTopicSearchValue.value = '';
    screeningModifyTopicValue.value = 'null';
    modifyTopicSearchValue.value = '';
  };
</script>
